# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import bcoma
import datetime

from wowgae.model import WowItemIcon
from wowgae.model import WowSpellIcon


class WowIconLoader(object):
    """Helps loading icon information for items and spells."""

    def __init__(self, timeout=30):
        self.start = datetime.datetime.utcnow()
        self.stop = self.start + datetime.timedelta(0, timeout)

    @classmethod
    def unknown_icon(cls):
        return cls.icon_uri('inv_misc_questionmark')

    @classmethod
    def icon_uri(self, name):
        base = 'http://us.media.blizzard.com/wow/icons/18/%s.jpg'
        return base % (name.lower())

    def _download_item(self, wow_id):
        item = bcoma.Item.fetch(wow_id)
        if item:
            return {'name': item.name, 'icon': item.icon,
                    'quality': item.quality, 'description': item.description}
        else:
            return False

    def _download_spell(self, wow_id):
        spell = bcoma.Spell.fetch(wow_id)
        if spell:
            return {'name': spell.name, 'icon': spell.icon}
        else:
            return False

    def _timeout_expired(self):
        return datetime.datetime.utcnow() >= self.stop

    def load_for(self, kind, wow_id):
        """Load icon information for the given Wow element.

        Returns None if the information could not be gathered or False if the
        identifier points to no object at all.

        """
        if self._timeout_expired():
            return None
        if kind == 'item':
            model = WowItemIcon
            download = self._download_item
        elif kind == 'spell':
            model = WowSpellIcon
            download = self._download_spell
        else:
            return False
        entity = model.get_by_wow_id(wow_id)
        if entity == False:
            return False
        elif entity is None:
            try:
                data = download(wow_id)
                return data and model.set_by_wow_id(wow_id, **data)
            except:
                return None
        else:
            return entity

    @classmethod
    def klass_icon(cls, klass):
        uri = 'http://us.media.blizzard.com/wow/icons/18/class_%s.jpg'
        return uri % (klass)

    @classmethod
    def race_icon(cls, race, faction):
        uri = 'http://us.media.blizzard.com/wow/icons/18/race_%s_%s.jpg'
        return uri % (race, faction)
